import { defineStore } from "pinia";
import { uGetStorageSync, uSetStorageSync } from "../utils/uniUtils";
import { reqPost } from "../common/http.request";
import { useShop } from "./useShop";

export const useUser = defineStore("user", {
  state: () => ({
    hasLogin: false,
    userInfo: {},
    shop_appid: 0,
    store: {},
    systemAppId: "",
	name: 'hi,zhuli',
	age: 30,
	color: '#e15852',//全局颜色
	Btntitle: '立即购买',//
	couponNumber: 0,
	cardNumber: 0,
	
  }),
  actions: {
    login(dt) {
      this.userInfo = dt.userInfo;
      this.shop_appid = dt.shop_appid; // token
      this.systemAppId = dt.systemAppId;
      this.store = dt.store;
      uSetStorageSync("userInfo", dt.userInfo);
      uSetStorageSync("shop_appid", dt.shop_appid);
      uSetStorageSync("systemAppId", dt.systemAppId);
      uSetStorageSync("store", dt.store);
      uSetStorageSync("user", dt.dt_user);
      uSetStorageSync("stock", dt.dt_stock);
      uSetStorageSync("member", dt.dt_member);
    },
    logout() {
      this.$reset();
      /*       uni.clearStorageSync("userInfo"); 
      uni.clearStorageSync("shop_appid");
      uni.clearStorageSync("hasLogin");
      uni.clearStorageSync("systemAppId");
      uni.clearStorageSync("store");
      uni.clearStorageSync("user");
      uni.clearStorageSync("stock");
      uni.clearStorageSync("member"); */
      uni.clearStorageSync();
    },
    async appLogin() {
      //获取当前帐号信息，可以返回小程序的Appid
      const accountInfo = uni.getAccountInfoSync();

      uni.login({
        success: async (res) => {
          const dt = await reqPost("OnUserLogin", {
            appId: accountInfo.miniProgram.appId,
            code: res.code,
            ...uGetStorageSync("m_store_info"),
          });

          const details = dt.Data[0];
          this.userInfo = details.userInfo;
          details &&
            Object.entries(details).forEach((item) => {
              uSetStorageSync(item[0], item[1]);
            });

          if (uGetStorageSync("hasLogin")) {
            this.hasLogin = true;
            useShop().GetShoppingCart();
          }
        },
        fail() {
          console.log("fail");
        },
      });
    },
  },
});
